package com.demo.flightInfo;

import java.util.Date;
import java.util.List;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.demo.common.constant.ConstantDtoFlight;
import com.demo.common.dto.DtoFlightResult;
import com.demo.common.model.Flightinfo;
import com.demo.common.model.Flightno;
import com.demo.common.model.Flighttrends;
import com.demo.common.model.Proxyip;
import com.demo.common.tool.ToolTime;
import com.demo.webmagic.dto.DtoFlightInfo;
import com.demo.webmagic.pageProcessor.PageProcessorVeryZhunFlighInfo;
import com.demo.webmagic.pipeline.PipelineVeryZhunFlightInfo;
import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.log.Log;
import com.jfinal.plugin.ehcache.CacheKit;

import us.codecraft.webmagic.Spider;

public class FlightInfoController extends Controller {

	private static final Log log = Log.getLog(FlightInfoController.class);

	public void index() {
		
	}

	/**
	 * 根据传过来的航班号查询 请求url设定：http://localhost/flightinfo/search?fno=xxxx
	 * 
	 * @return
	 */
	@Before(FlightNoValidator.class)
	public void searchJson() {
		// 1.获取航班号
		String fno = getPara("fno");
		// 2.转大写
		fno = fno.toUpperCase();
		// 3.根据fno和当天的时间生成key
		String key = fno + "#" + ToolTime.getNowTimeStr("yyyy-MM-dd");
		// 4.通过key从缓存中获取数据
		DtoFlightInfo result = CacheKit.get("flight", key);
		// 5.判断数据是否存在
		if (result == null) {
			result = Flightinfo.dao.getByFno(fno);
			if (result == null) {
				// 5.1如果不存在，则通过http请求获取数据
				log.debug("缓存中不存在数据，通过http访问获取数据");
				try {
					result = getFlightInfoByVeryZhun(fno);
					CacheKit.put("flight", key, result);
				} catch (Exception e) {
					log.error(e.getMessage());
					result = new DtoFlightInfo();
					result.setCode(ConstantDtoFlight.code_fail);
					result.setMessage(ConstantDtoFlight.message_fno_fail);
				}
			} else {
				CacheKit.put("flight", key, result);
				renderJson(result);
				return;
			}
		} else {
			// 5.2如果缓存中有数据，则分析是否需要通过http请求数据
			if (ToolTime.getIntervalMinute(result.getSearchTime(), new Date()) > ConstantDtoFlight.polling_interval) {
				List<Flighttrends> trendsList = result.getTrendsList();
				boolean flag = true;
				for (Flighttrends flighttrends : trendsList) {
					String flightStatus = flighttrends.getFlightStatus();
					if (!"已经到达".equals(flightStatus) && !"已经取消".equals(flightStatus)) {
						flag = false;
						break;
					}
				}
				if (flag) {
					result.setEnd(true);
					CacheKit.put("flight", key, result);
				} else {
					log.debug("缓存中不存在数据，通过http访问获取数据");
					try {
						result = getFlightInfoByVeryZhun(fno);
						CacheKit.put("flight", key, result);
					} catch (Exception e) {
						log.error(e.getMessage());
						result = new DtoFlightInfo();
						result.setCode(ConstantDtoFlight.code_fail);
						result.setMessage(ConstantDtoFlight.message_fno_fail);
					}
				}
			}
		}
		// 返回json数据
		renderJson(result);
	}

	private DtoFlightInfo getFlightInfoByVeryZhun(String fno) throws Exception {
		DtoFlightInfo result;
		String url = "http://www.veryzhun.com/searchnum2.asp?flightnum=" + fno;
		PageProcessorVeryZhunFlighInfo veryZhunFlighInfo = new PageProcessorVeryZhunFlighInfo(
				Proxyip.dao.getValiProxyip());
		Spider.create(veryZhunFlighInfo).addUrl(url).addPipeline(new PipelineVeryZhunFlightInfo()).run();
		result = veryZhunFlighInfo.getDtoFlightInfo();
		result.setSearchTime(new Date());
		if (result.getFlightInfo() != null) {
			Flightno flightno = Flightno.dao.findFirst("SELECT * FROM flightno WHERE fno = ?", fno);
			if (flightno == null) {
				flightno = new Flightno();
				flightno.setFno(fno);
				flightno.save();
			}
		}
		return result;
	}

	/*
	 * private DtoFlightResult getFlightInfoByVeryZhun(String fno) throws
	 * Exception { DtoFlightResult dtoFlightResult = new DtoFlightResult();
	 * 
	 * String url = "http://www.veryzhun.com/searchnum2.asp?flightnum=" + fno;
	 * 
	 * Document doc = Jsoup.connect(url).get(); Elements qfList =
	 * doc.select("div[class=numdap]"); Elements info =
	 * doc.select("div[class=numinfo]"); Elements ddList =
	 * doc.select("div[class=numarr]");
	 * 
	 * Element qfElement = qfList.get(0); Elements qfTimeList =
	 * qfElement.select("div[class=numtime]").first().children(); try {
	 * System.out.println(qfTimeList.get(0).text()); } catch(Exception e) {
	 * System.out.println("计划起飞: --:--"); } try {
	 * System.out.println(qfTimeList.get(1).text()); } catch(Exception e) {
	 * System.out.println("预计起飞: --:--"); } try {
	 * System.out.println(qfTimeList.get(2).text()); } catch(Exception e) {
	 * System.out.println("预计起飞: --:--"); }
	 * 
	 * Element ddElement = ddList.get(0); Elements ddTimeList =
	 * ddElement.select("div[class=numtime]").first().children(); try {
	 * System.out.println(ddTimeList.get(0).text()); } catch(Exception e) {
	 * System.out.println("计划到达: --:--"); } try {
	 * System.out.println(ddTimeList.get(1).text()); } catch(Exception e) {
	 * System.out.println("预计到达: --:--"); } try {
	 * System.out.println(ddTimeList.get(2).text()); } catch(Exception e) {
	 * System.out.println("预计到达: --:--"); }
	 * 
	 * System.out.println(qfElement.select("li[class=num_here]").first().text())
	 * ;
	 * System.out.println(ddElement.select("li[class=num_here]").first().text())
	 * ;
	 * 
	 * System.out.println("准点率：" +
	 * info.select("span[class=red]").first().text());
	 * System.out.println("飞机状态：" +
	 * info.select("td[class=airname]").first().text());
	 * 
	 * for (int i = 0; i < qfList.size(); i++) { qfList.get(i); }
	 * 
	 * 
	 * return dtoFlightResult; }
	 */

	public static void main(String[] args) {
		String str = "机型：历史准点率：85.19%";
		System.out.println(str.substring(str.lastIndexOf("：") + 1, str.length()));
		/*
		 * FlightInfoController controller = new FlightInfoController(); try {
		 * //controller.getFlightInfoByVeryZhun("G52685"); } catch (Exception e)
		 * { e.printStackTrace(); }
		 * 
		 * PageProcessorVeryZhunFlighInfo veryZhunFlighInfo = new
		 * PageProcessorVeryZhunFlighInfo();
		 * Spider.create(veryZhunFlighInfo).addUrl(
		 * "http://www.veryzhun.com/searchnum2.asp?flightnum=G52685").run();
		 * System.out.println(veryZhunFlighInfo.getDtoFlightInfo().getFlightInfo
		 * ().getZdl());
		 */
	}
}
